﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;


namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    /// TMS运单发货数量回写
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TMSShippingOrderPriceUpdateController : ControllerBase
    {
        private readonly ILogger<TMSShippingorder_PriceUpdateRequestDto> _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;
        public readonly string con_wms_zh;
        public readonly string con_wms_qh;
        public readonly string con_wms_sc;
        public readonly string con_wms_gd;
        public readonly string con_wms_gz;

        public TMSShippingOrderPriceUpdateController(ILogger<TMSShippingorder_PriceUpdateRequestDto> logger,IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration)
        {
            _logger = logger;
            _WMSTokenCheckService = wmsTokenCheckService;
             con= _configuration.GetConnectionString("DDM_DbConnection_ZH");
            con_wms_zh = _configuration.GetConnectionString("WMSDbConnection_ZH");
            con_wms_qh = _configuration.GetConnectionString("WMSDbConnection");
            con_wms_sc = _configuration.GetConnectionString("WMSDbConnection_YB");
            con_wms_gd= _configuration.GetConnectionString("WMSDbConnection_GD");
            con_wms_gz = _configuration.GetConnectionString("WMSDbConnection_GZ");

        }

        /// <summary>
        /// TMS运单发货数量回写
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostTMSShippingOrderPriceUpdate([FromBody] TMSShippingorder_PriceUpdateRequestDto strparm)
        {
            string  strMsg = "";
            object log = "";
            log = strparm;
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            TMSShippingorder_PriceUpdateResponseDto re = new TMSShippingorder_PriceUpdateResponseDto();
            string shippingorderno = strparm.shippingorderno;
            string con_jd = "";
            //框架查询方法
            //var data = _WMSTokenCheckService.GetTokenCheckData(supplier_code);
            decimal cprice = 0;
            decimal qty = 0;

            try
            {

                strSql = new StringBuilder();
                strSql.Append(@" select shippingorderno,sum(cprice)cprice,sum(car_pooling)car_pooling from shippingorder_plan_details 
where shippingorderno='" + shippingorderno + "'  group by shippingorderno");
                DataTable dt_price = DB.Query(strSql.ToString(), con);
                if (dt_price.Rows.Count>0)
                {
                    cprice = DB.ToDecimal(dt_price.Rows[0]["cprice"].ToString())+ DB.ToDecimal(dt_price.Rows[0]["car_pooling"].ToString());





                    strSqlList = new List<string>();
                    strSql = new StringBuilder();
                    strSql.Append(@"select main.factory_code,main.factory_id,del.shippingorderno,del.sales_order_no,del.sales_order_id,del.customer_code,del.customer_name,del.sales_order_line_id,del.material_code,del.material_name,del.material_unit,del.material_amount,del.target_address from shippingorder_sales_details del join 
 shippingorder_main  main on del.shippingorderno=main.ccode   where del.shippingorderno='" + shippingorderno + "' ");
                    DataTable dt_sales_details = DB.Query(strSql.ToString(), con);
                    if (dt_sales_details.Rows.Count > 0)
                    {
                        foreach (DataRow item in dt_sales_details.Rows)
                        {
                            string sales_order_line_id = item["sales_order_line_id"].ToString();
                            string factory_id = item["factory_id"].ToString();
                            string sales_order_no = item["sales_order_no"].ToString();
                            string material_code = item["material_code"].ToString();

                            if (factory_id.Contains("A01"))
                            {
                                con_jd = con_wms_gd;
                            }
                            else if (factory_id.Contains("B01"))
                            {
                                con_jd = con_wms_qh;
                            }
                            else if (factory_id.Contains("E01"))
                            {
                                con_jd = con_wms_sc;
                            }
                            else if(factory_id.Contains("G01"))
                            {
                                con_jd = con_wms_gz;
                            }
                            else
                            {
                                con_jd = con_wms_zh;
                            }


                            string eer = "";

                            strSql = new StringBuilder();
                            strSql.Append(@"select tms.shipping_order_no,ship.source_no,tms.sales_order_line_id,tms.shipment_no,spc.waybill_no,ship.material_code,ship.material_name,ship.material_amount from 
(select DISTINCT shipping_order_no,sales_order_line_id,shipment_no from tms_logistics_scan_record ) tms left join (select shipment_no,source_no,material_code,material_name,source_item_code,sum(material_amount)material_amount  from shipment_scan_record ship where shipment_no is not null group by shipment_no,material_code,material_name,source_item_code,source_no ) ship on (tms.sales_order_line_id=
ship.source_item_code  and tms.shipment_no=ship.shipment_no) left  join  (select distinct shipment_no,waybill_no from shipment_order) spc on tms.shipment_no=spc.shipment_no  where tms.shipping_order_no='" + shippingorderno + "' and ship.material_code='" + material_code + "'  and ship.source_no='"+ sales_order_no + "'");
                            DataTable dt_wms_sl = DB.Query(strSql.ToString(), con_jd);
                            if (dt_wms_sl.Rows.Count > 0)
                            {
                                strSql = new StringBuilder();
                                strSql.Append(@" update shippingorder_sales_details  set wms_amount="+ dt_wms_sl.Rows[0]["material_amount"].ToString()+ ",delivery_no='"+ dt_wms_sl.Rows[0]["waybill_no"].ToString() + "',outbound_no='"+ dt_wms_sl.Rows[0]["shipment_no"].ToString() + "'   where shippingorderno='" + shippingorderno + "' and sales_order_no='" + sales_order_no + "' and  material_code='"+ material_code + "'");
                                strSqlList.Add(strSql.ToString());
                            }
                            else
                            {
                                eer = "订单《" + sales_order_no + "》获取运单出货记录失败,请确认仓库是否PDA选择车牌信息发货,确认失败;";
                                strMsg = strMsg + eer;
                            }

                        }

                        string kz = "";
                        strSql = new StringBuilder();
                        strSql.Append(@"select * from tms_control where controlid='KZ0001'");
                        DataTable dt_kz = DB.Query(strSql.ToString(), con);
                        if (dt_kz.Rows.Count>0)
                        {
                            kz = dt_kz.Rows[0]["isopen"].ToString();
                        }


                        if (kz=="1")
                        {
                            if (strMsg=="")
                            {
                                if (strSqlList.Count > 0)
                                {
                                    bool A = DB.ExecuteNoQueryTran(strSqlList, con);
                                    if (A)
                                    {

                                    }
                                    else
                                    {
                                        strMsg = "数据库更新失败，请联系管理员";
                                    }
                                }
                            }

                        }
                        else
                        {
                            if (strSqlList.Count > 0)
                            {
                                bool A = DB.ExecuteNoQueryTran(strSqlList, con);
                                if (A)
                                {
                                    strMsg = "";
                                }
                                else
                                {
                                    strMsg = "数据库更新失败，请联系管理员";
                                }
                            }

                            strMsg = "";

                        }

                       
                        
                    }
                    else
                    {
                        strMsg = "请确认物流运单是否数据丢失或删除,确认失败";
                    }
                }





               

            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }

         


            if (strMsg=="")
            {
                re.status = "成功";
                re.code = "0";
            }
            else
            {
                re.status = "失败";
                re.code = "500";
                re.message = strMsg;
            }


            return new JsonResult(re);
        }

      
    }
}
